"""
需求管理服务层
"""

from sqlalchemy.orm import Session
from sqlalchemy import and_, or_
from typing import List, Optional
from datetime import datetime

from ..models.requirement import Requirement
from ..schemas.requirement import RequirementCreate, RequirementUpdate


class RequirementService:
    """需求管理服务"""
    
    def get_requirements(
        self,
        db: Session,
        page: int = 1,
        page_size: int = 20,
        search: Optional[str] = None,
        tag_filter: Optional[str] = None,
        created_by: Optional[int] = None
    ) -> List[Requirement]:
        """获取需求列表"""
        query = db.query(Requirement)
        
        # 按创建者筛选
        if created_by:
            query = query.filter(Requirement.creator_id == created_by)
        
        # 搜索功能
        if search:
            search_filter = or_(
                Requirement.title.contains(search),
                Requirement.description.contains(search),
                Requirement.content.contains(search)
            )
            query = query.filter(search_filter)
        
        # 标签筛选
        if tag_filter:
            query = query.filter(Requirement.tags.contains([tag_filter]))
        
        # 分页
        offset = (page - 1) * page_size
        requirements = query.order_by(Requirement.created_at.desc()).offset(offset).limit(page_size).all()
        
        return requirements
    
    def create_requirement(
        self,
        db: Session,
        requirement: RequirementCreate,
        created_by: int
    ) -> Requirement:
        """创建需求"""
        db_requirement = Requirement(
            title=requirement.title,
            description=requirement.description,
            content=requirement.content,
            tags=requirement.tags or [],
            created_by=created_by,
            created_at=datetime.utcnow()
        )
        
        db.add(db_requirement)
        db.commit()
        db.refresh(db_requirement)
        
        return db_requirement
    
    def get_requirement_by_id(
        self,
        db: Session,
        requirement_id: int,
        user_id: Optional[int] = None
    ) -> Optional[Requirement]:
        """根据ID获取需求"""
        query = db.query(Requirement).filter(Requirement.id == requirement_id)
        
        # 如果指定了用户ID，则只返回该用户的需求
        if user_id:
            query = query.filter(Requirement.created_by == user_id)
        
        return query.first()
    
    def update_requirement(
        self,
        db: Session,
        requirement_id: int,
        requirement: RequirementUpdate,
        user_id: int
    ) -> Optional[Requirement]:
        """更新需求"""
        db_requirement = self.get_requirement_by_id(db, requirement_id, user_id)
        if not db_requirement:
            return None
        
        # 更新字段
        update_data = requirement.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_requirement, field, value)
        
        db_requirement.updated_at = datetime.utcnow()
        
        db.commit()
        db.refresh(db_requirement)
        
        return db_requirement
    
    def delete_requirement(
        self,
        db: Session,
        requirement_id: int,
        user_id: int
    ) -> bool:
        """删除需求"""
        db_requirement = self.get_requirement_by_id(db, requirement_id, user_id)
        if not db_requirement:
            return False
        
        db.delete(db_requirement)
        db.commit()
        
        return True 